//
//  ImagesController.m
//  BSProject
//
//  Created by nsm on 2019/7/8.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "ImagesController1.h"
#import "NSMPhotosView.h"

@interface ImagesController1 ()
@property (nonatomic, strong) MyLinearLayout *layout;
@property (nonatomic, strong) NSMPhotosView *avatar;
@property (nonatomic, strong) NSMPhotosView *cers;
@property (nonatomic, strong) NSMPhotosView *cards;

@property (nonatomic, strong) MyBaseLayout *stepsLayout;
@property (nonatomic) NSUInteger materialIndex;
@property (nonatomic) NSUInteger stepIndex;
@property (nonatomic, strong) NSMutableArray<NSMPhotosView *> *jobs;
@end

@implementation ImagesController1

#pragma mark - lifeCycle

#pragma mark - override
- (void)loadView {
    self.view = UIScrollView.new;
}

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem *submit = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(submit)];
    self.navigationItem.rightBarButtonItem = submit;
    
    [self reloadImages:nil];
    
    UIScrollView *s = (UIScrollView *)self.view;
    s.headerRefreshEnabled = YES;
    s.urlString = @"demo/imageUpload";
    
    @nsm_weak(self)
    s.didRefreshingFooterSuccess = ^(id responseObject) {
        @nsm_strong(self)
        id data = ((NSMResponseObject *)responseObject).data;
        // [self reloadImages:data];
    };
    [s beginRefreshing:RefreshHudDefault];
}

- (void)initSubviews {
    [super initSubviews];
    
    _layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    _layout.backgroundColor = COLOR_4;
    _layout.myHorzMargin = 0;
    _layout.padding = UIEdgeInsetsMake(20, 0, 20, 0);
    _layout.subviewVSpace = 20;
    [self.view addSubview:_layout];
}

- (void)reloadImages:(id)obj {
    [self.layout removeAllSubviews];
    
    {
        // 由于NSMPhotosView内部实现是以水平填充为准.即使设置size也无法改变。所以包裹一层视图.同时亦可以实现更多功能,比如边框、阴影
        UIView *avatarBG = UIView.new;
        avatarBG.size = CGSizeMake(100, 100);
        avatarBG.myAlignment = MyGravity_Horz_Center;
        [_layout addSubview:avatarBG];
        
        avatarBG.layer.shadowColor = UIColor.blackColor.CGColor;
        avatarBG.layer.shadowOffset = CGSizeMake(0, 0);
        avatarBG.layer.shadowOpacity = 0.7;
        avatarBG.layer.shadowRadius = 5;
        
        NSMPhotosView *pv = NSMPhotosView.new;
        pv.backgroundColor = UIColor.whiteColor;
        
        // 最大一张
        pv.arrangedCount = 1;
        pv.maximumNumberOfPhotos = 1;
        
        // 去掉默认边距
        pv.padding = UIEdgeInsetsZero;
        
        pv.editEnabled = YES;
        [avatarBG addSubview:pv];
        ViewCorner(pv, 50);
        _avatar = pv;
    }
    
    {
        NSMPhotosView *pv = NSMPhotosView.new;
        pv.backgroundColor = RandomColor();
        pv.arrangedCount = 5;
        pv.maximumNumberOfPhotos = 9;
        pv.editEnabled = YES;
        pv.deleteEnabled = YES;
        [_layout addSubview:pv];
        _cards = pv;
    }
    
    {
        NSMPhotosView *pv = NSMPhotosView.new;
        pv.backgroundColor = RandomColor();
        pv.arrangedCount = 4;
        pv.maximumNumberOfPhotos = 8;
        pv.editEnabled = YES;
        pv.deleteEnabled = YES;
        [_layout addSubview:pv];
        _cers = pv;
    }
    
    [_layout addSubview:[self layoutForStep]];
}

- (UIView *)layoutForStep {
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.myHorzMargin = 0;
    layout.backgroundColor = COLOR_4;
    layout.gravity = MyGravity_Horz_Fill;
    self.stepsLayout = layout;
    
    [layout addSubview:[self titleView:@"工作经历\n"
                              subTitle:@"按顺序以图片+文字的形式详细描"
                                 image:nil]];
    
    [layout addSubview:[self itemLayoutForStep]];
    
    NSMButton *addBtn = [NSMButton new];
    addBtn.myHeight = 54;
    addBtn.imageSize = CGSizeMake(21, 21);
    addBtn.adjustsImageTintColorAutomatically = YES;
    addBtn.adjustsTitleTintColorAutomatically = YES;
    addBtn.titleLabel.font = CustomFont(15);
    addBtn.tintColor = THEME_COLOR;
    [addBtn setTitle:@"增加一项" forState:UIControlStateNormal];
    [addBtn setImage:NameImage(@"icon_add_line") forState:UIControlStateNormal];
    [layout addSubview:addBtn];
    
    @nsm_weak(self)
    @nsm_weak(layout)
    [addBtn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        @nsm_strong(self)
        @nsm_strong(layout)
        [layout insertSubview:[self itemLayoutForStep] atIndex:layout.subviews.count-1];
    }];
    
    return layout;
}

- (NSUInteger)numberOfSteps {
    NSUInteger count = 0;
    for (UIView *view in self.stepsLayout.subviews) {
        if ([view.identifierEx isEqual:@"step_layout"]) {
            count ++;
        }
    }
    return count;
}

- (MyLinearLayout *)itemLayoutForStep {
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.gravity = MyGravity_Horz_Fill;
    layout.identifierEx = @"step_layout";
    
    MyBorderline *line = [[MyBorderline alloc] initWithColor:SEPARATOR_COLOR];
    line.headIndent = 15;
    line.tailIndent = 15;
    layout.bottomBorderline = line;
    
    MyLinearLayout *headerLayout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
    headerLayout.padding = UIEdgeInsetsMake(0, 15, 0, 0);
    headerLayout.myHeight = 44;
    headerLayout.gravity = MyGravity_Vert_Fill;
    [layout addSubview:headerLayout];
    
    // 实时工作经历数
    NSUInteger numberOfSteps = [self numberOfSteps];
    // 防止数据重复
    NSUInteger maskCode = ++self.stepIndex;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.tag = 88;
    titleLabel.weight = 1;
    titleLabel.font = BoldSystemFont(15);
    titleLabel.textColor = COLOR_1;
    titleLabel.text = FormatString(@"工作经历%@", @(numberOfSteps+1));
    [headerLayout addSubview:titleLabel];
    
    NSMButton *btn = [NSMButton new];
    btn.wrapContentWidth = YES;
    btn.imageSize = CGSizeMake(24, 24);
    btn.spacing = 1;
    btn.tintColor = THEME_COLOR;
    btn.titleLabel.font = CustomFont(13);
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 12);
    btn.adjustsImageTintColorAutomatically = YES;
    btn.adjustsTitleTintColorAutomatically = YES;
    [btn setTitle:@"删除" forState:UIControlStateNormal];
    [btn setImage:NameImage(@"nsm_delete_bucket") forState:UIControlStateNormal];
    [headerLayout addSubview:btn];
    
    NSMPhotosView *photosView = [NSMPhotosView photoView];
    photosView.identifierEx = IntegerString(maskCode);
    photosView.backgroundColor = COLOR_5;
    photosView.padding = UIEdgeInsetsMake(0, 15, 0, 15);
    photosView.arrangedCount = 3;
    photosView.tag = 99;
    photosView.maximumNumberOfPhotos = 3;
    photosView.editEnabled = YES;
    photosView.deleteEnabled = NO;
    [layout addSubview:photosView];
    [self.jobs addObject:photosView];
    
    NSMTextView *textView = [[NSMTextView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth-10*2, 120)];
    textView.tag = 100;
    textView.maskCode = maskCode;
    textView.mark = @"step";
    textView.identifierEx = @"name";
    textView.myHorzMargin = 10;
    textView.myHeight = 120;
    textView.myBottom = 12;
    textView.font = CustomFont(14);
    textView.placeholder = @"添加工作经历描述";
    [layout addSubview:textView];
    
    @nsm_weak(self)
    @nsm_weak(layout)
    [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        @nsm_strong(self)
        @nsm_strong(layout)
        [layout removeFromSuperview];
        [self.jobs removeObject:photosView];
        
        NSUInteger count = 0;
        for (UIView *view in self.stepsLayout.subviews) {
            if ([view.identifierEx isEqual:@"step_layout"]) {
                NSUInteger newStep = ++count;
                UILabel *tempLabel = (UILabel *)[view viewWithTag:88];
                NSMPhotosView * tempPhotoView = (NSMPhotosView *)[view viewWithTag:99];
                tempLabel.text = FormatString(@"工作经历%@", @(newStep));
                // 重新定义图片的所在的工作经历
                tempPhotoView.identifierEx = IntegerString(newStep);
            }
        }
    }];
    
    return layout;
}

- (UIView *)titleView:(NSString *)title subTitle:(NSString *)subTitle image:(NSString *)imageName {
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.padding = UIEdgeInsetsMake(12, 15, 12, 15);
    layout.gravity = MyGravity_Horz_Fill;
    
    MyBorderline *line = [[MyBorderline alloc] initWithColor:SEPARATOR_COLOR];
    line.headIndent = 15;
    line.tailIndent = 15;
    layout.bottomBorderline = line;
    
    NSMButton *btn = [NSMButton new];
    if (imageName) {
        btn.imageSize = CGSizeMake(27, 27);
        btn.spacing = 8;
        btn.imagePosition = NSMButtonImagePositionRight;
    }
    btn.wrapContentHeight = YES;
    btn.adjustsWhenDisabled = NO;
    btn.enabled = NO;
    btn.titleLabel.numberOfLines = 0;
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [btn setTitleColor:COLOR_0 forState:UIControlStateNormal];
    [btn setAttributedTitle:AttributedString(title,
                                             BoldSystemFont(16),
                                             COLOR_0,
                                             subTitle,
                                             CustomFont(13),
                                             SUB_TEXT_COLOR,
                                             NSTextAlignmentLeft,
                                             2)
                   forState:UIControlStateNormal];
    [layout addSubview:btn];
    
    return layout;
}

#pragma mark - setter/getter

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private

#pragma mark - action
- (void)submit {
    
    // 基本的文字字段
    NSMutableArray *jobsArray = @[].mutableCopy;
    // 因为一个视图的子视图里不一定全是指定的视图,所以自定义一个下标count
    NSUInteger count = 0;
    for (UIView *view in self.stepsLayout.subviews) {
        if ([view.identifierEx isEqual:@"step_layout"]) {
            count ++;
            NSMTextView *textView = (NSMTextView *)[view viewWithTag:100];
            NSMPhotosView *photoView = (NSMPhotosView *)[view viewWithTag:99];
            NSString *fieldName = FormatString(@"jobs_%zd",count);
            photoView.identifierEx = fieldName;
            NSString *text = SafeString(textView.text);
            [jobsArray addObject:@{@"title": text, @"image_field": fieldName}];
        }
    }
    
    NSDictionary *param = @{@"steps": jobsArray.jsonStringEncoded};
    [_networker POST:@"demo/imageUpload" parameters:param formDataBlock:^(id<AFMultipartFormData> formData) {
        // 头像(单图)
        NSMPhotoImageView *avatar = self.avatar.photoViews.firstObject;
        if (avatar.image) {
            [formData appendPartWithFileData:UIImageJPEGRepresentation(avatar.image, 0.7)
                                        name:@"avatar"
                                    fileName:@"avatar.jpg"
                                    mimeType:@"image/jpeg"];
        }
        // 2.身份证件(多图,2张)1.jpg 2.jpg
        for (int i=0; i<self.cards.photoViews.count; i++) {
            NSMPhotoImageView *imageView = self.cards.photoViews[i];
            if (imageView.image) {
                [formData appendPartWithFileData:UIImageJPEGRepresentation(imageView.image, 0.7)
                                            name:@"cards[]"
                                        fileName:FormatString(@"%d.jpg",i+1)
                                        mimeType:@"image/jpeg"];
            }
        }
        // 2.荣誉证书(多图,不限)1.jpg 2.jpg
        for (int i=0; i<self.cers.photoViews.count; i++) {
            NSMPhotoImageView *imageView = self.cers.photoViews[i];
            if (imageView.image) {
                [formData appendPartWithFileData:UIImageJPEGRepresentation(imageView.image, 0.7)
                                            name:@"cers[]"
                                        fileName:FormatString(@"%d.jpg",i+1)
                                        mimeType:@"image/jpeg"];
            }
        }
        // 3.工作经历(动态图片字段)
        for (int i=0; i<self.jobs.count; i++) {
            NSMPhotosView *job = self.jobs[i];
            for (int j=0; j<job.photoViews.count; j++) {
                NSMPhotoImageView *imageView = job.photoViews[j];
                if (imageView.image) {
                    /*
                     1.name     接口的图片字段动态 这里取标志符号（也可以下标 job_i[]）
                     2.fileName 图片的名字（简单以下标命名）
                     */
                    [formData appendPartWithFileData:UIImageJPEGRepresentation(imageView.image, 0.7)
                                                name:FormatString(@"%@[]",job.identifierEx)
                                            fileName:FormatString(@"%d.jpg",j+1)
                                            mimeType:@"image/jpeg"];
                }
            }
        }
    } progress:^(NSProgress *uploadProgress) {
        
    } success:^(NSMResponseObject *responseObject) {
        
    } empty:^(NSMResponseObject *responseObject) {
    } failure:^(NSError *error) {
    } hud:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
